package com.jcfk.system.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.LoginInfo;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.dao.SysFrequentMenuDao;
import com.jcfk.system.domain.dto.SysFrequentMenuDTO;
import com.jcfk.system.domain.po.SysFrequentMenu;
import com.jcfk.system.domain.query.SysFrequentMenuQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 常用菜单表
 *
 * @author yrl
 * @email
 * @date 2025-06-03
 */
@Service
public class SysFrequentMenuService extends BaseService<SysFrequentMenuDao, SysFrequentMenu> {

    @Resource
    private SysPermissionService sysPermissionService;


    /**
     * SysFrequentMenu分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysFrequentMenuDTO> queryByPage(DataPage<SysFrequentMenuDTO> page, SysFrequentMenuQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断SysFrequentMenu是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysFrequentMenuDTO dto) {
        QueryWrapper<SysFrequentMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入常用菜单表
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysFrequentMenuDTO dto) {
        String userId = SecurityUtils.getUserId();
        Assert.notNull(userId, "用户ID不能为空");
        // 删除原有数据
        this.remove(Wrappers.<SysFrequentMenu>lambdaQuery().eq(SysFrequentMenu::getUserId, userId));

        List<SysFrequentMenu> sysFrequentMenus = dto.getMenuIds().stream().map(menuId -> {
            SysFrequentMenu item = new SysFrequentMenu();
            this.setDefaultValue(item);
            item.setUserId(userId);
            item.setPermissionId(menuId);
            return item;
        }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(sysFrequentMenus)) this.saveBatch(sysFrequentMenus);
    }

    /**
     * 更新常用菜单表
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SysFrequentMenuDTO dto) {

        // 保存
        SysFrequentMenu item = new SysFrequentMenu();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除常用菜单表(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysFrequentMenuDTO dto) {

        SysFrequentMenu item = new SysFrequentMenu();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<SysFrequentMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysFrequentMenu item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取常用菜单表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysFrequentMenuDTO get(String id) {
        // 查询数据
        SysFrequentMenu item = this.baseMapper.selectById(id);
        SysFrequentMenuDTO dto = new SysFrequentMenuDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<SysFrequentMenuDTO>
     */
    public List<SysFrequentMenuDTO> getList(SysFrequentMenuQuery query) {
        // 查询条件
        QueryWrapper<SysFrequentMenu> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getPermissionId()), SysFrequentMenu::getPermissionId, query.getPermissionId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getUserId()), SysFrequentMenu::getUserId, query.getUserId());
        // 查询数据
        List<SysFrequentMenu> list = super.list(qw);

        return convertList(list, SysFrequentMenuDTO.class);
    }

    /**
     * 根据主键获取常用菜单表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        SysFrequentMenu item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    public List<SysFrequentMenuDTO> tree(String permissionType) {
        List<SysFrequentMenuDTO> tree = new ArrayList<>();
        List<SysFrequentMenuDTO> sysFrequentMenuDTOS = new ArrayList<>();
        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();
        Assert.notNull(loginInfo, "用户信息不能为空");
        String userId = loginInfo.getUserId();
        // 超级管理员
        if ("superadmin".equals(loginInfo.getUserType()))
            sysFrequentMenuDTOS = this.baseMapper.getListByAdmin(userId, permissionType);
        else
            sysFrequentMenuDTOS = this.baseMapper.getListByUserId(userId, permissionType);

        Map<String, SysFrequentMenuDTO> frequentMenuDTOMap = sysFrequentMenuDTOS.stream().collect(Collectors.toMap(SysFrequentMenuDTO::getPermissionId, Function.identity()));
        for (SysFrequentMenuDTO node : sysFrequentMenuDTOS) {
            String parentId = node.getParentId();
            SysFrequentMenuDTO parentNode = frequentMenuDTOMap.get(parentId);
            if (parentNode == null) {
                tree.add(node);
            } else {
                if (parentNode.getChildren() == null) {
                    parentNode.setChildren(new ArrayList<>());
                }
                parentNode.getChildren().add(node);
            }
        }

        return tree;
    }

    public List<SysFrequentMenuDTO> getOwnList(String permissionType) {
        LoginInfo loginInfo = LoginUserInfoUtils.getUserInfo();
        Assert.notNull(loginInfo, "用户信息不能为空");
        String userId = loginInfo.getUserId();
        // 超级管理员
        if ("superadmin".equals(loginInfo.getUserType())) {
            return this.baseMapper.getListByAdmin(userId, permissionType);
        }
        return this.baseMapper.getListByUserId(userId, permissionType);
    }
}

